<template>
  <f7-page>
    <f7-navbar>
      <f7-nav-left>
        <f7-link icon-f7="arrow_left" class="back link"></f7-link>
      </f7-nav-left>
      <f7-nav-title>文件预览</f7-nav-title>
      <f7-nav-right>
        <f7-link></f7-link>
      </f7-nav-right>
    </f7-navbar>
    <div class="offcie-container">
      <remote-js :srcArr="srcArr" @scriptLoad="scriptLoad"></remote-js>
      <div id="onlyoffice"></div>
    </div>
  </f7-page>
</template>
<script>
export default {
  props: {
    option: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      srcArr: [
        "./static/onlyoffice/api.js",
        //直接加载onlyoffice需要配置跨域
        // process.env.VUE_APP_ONLYOFFICE_URL +
        //   "/web-apps/apps/api/documents/api.js",
      ],
      docType: "",
      scriptDone: false,
      modelDone: false,
      loadDone: false,
      user: {},
    };
  },
  async created() {
    this.user = await this.$framework.account.getUser();
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      window.extensionParams = {
        url: this.$framework.config.api.onlyoffice,
      };
      this.option = {
        ...{
          url: this.$f7route.query.url,
          attachmentId: this.$f7route.query.attachmentId,
          title: this.$f7route.query.fileName,
          fileType: this.$f7route.query.fileName
            ? this.$f7route.query.fileName.substring(
                this.$f7route.query.fileName.lastIndexOf(".") + 1
              )
            : "doc",
        },
        ...this.option,
      };
      if (this.option.url) {
        this.modelDone = true;
        this.setEditor(this.option);
      } else if (this.option.attachmentId) {
        this.option.url =
          this.$framework.config.server +
          "/attachment/down/" +
          this.option.attachmentId;
        this.setEditorByAttachment(this.option.attachmentId);
      } else if (this.$attrs.attachmentId) {
        this.option.url =
          this.$framework.config.server +
          "/attachment/down/" +
          this.$attrs.attachmentId;
        this.setEditorByAttachment(this.$attrs.attachmentId);
      }
    },
    scriptLoad() {
      this.scriptDone = true;
      if (!this.initDone && this.modelDone) {
        this.setEditor(this.option);
      }
    },
    setEditorByAttachment(id) {
      this.$f7.request.postJSON(
        "/api/base/fileupload/getFile",
        { attachmentId: id },
        (r) => {
          if (r && r.parameters && r.parameters.file) {
            this.option.fileType = r.parameters.file.fileType.startsWith(".")
              ? r.parameters.file.fileType.substring(1)
              : r.parameters.file.fileType;
            this.option.title = r.parameters.file.fileName;
            this.option.attachmentId = id;
            this.option.uploadTime = r.parameters.file.uploadTime;
            this.option.uploaderName = r.parameters.file.uploaderName;
            this.modelDone = true;
            if (!this.initDone && this.scriptDone) {
              this.setEditor(this.option);
            }
          } else {
            this.$f7.dialog.alert("获取文件信息失败", () => {
              this.$f7.router.back();
            });
          }
        }
      );
    },
    handleDocType(fileType) {
      let docType = "";
      let fileTypesDoc = [
        "doc",
        "docm",
        "docx",
        "dot",
        "dotm",
        "dotx",
        "epub",
        "fodt",
        "htm",
        "html",
        "mht",
        "odt",
        "ott",
        "pdf",
        "rtf",
        "txt",
        "djvu",
        "xps",
        "wps",
      ];
      let fileTypesCsv = [
        "csv",
        "fods",
        "ods",
        "ots",
        "xls",
        "xlsm",
        "xlsx",
        "xlt",
        "xltm",
        "xltx",
        "et",
      ];
      let fileTypesPPt = [
        "fodp",
        "odp",
        "otp",
        "pot",
        "potm",
        "potx",
        "pps",
        "ppsm",
        "ppsx",
        "ppt",
        "pptm",
        "pptx",
        "dps",
      ];
      fileType = fileType.toLowerCase();
      if (fileType.startsWith(".")) {
        fileType = fileType.substring(1);
      }
      if (fileTypesDoc.includes(fileType)) {
        docType = "word";
      }
      if (fileTypesCsv.includes(fileType)) {
        docType = "cell";
      }
      if (fileTypesPPt.includes(fileType)) {
        docType = "slide";
      }
      return docType;
    },
    setEditor(option) {
      this.loadDone = true;

      option.permissions = option.permissions || {};

      this.docType = this.handleDocType(option.fileType);
      // office配置参数
      let config = {
        type: "mobile",
        width: "100%",
        height: "100%",
        documentType: this.docType,
        document: {
          title: option.title || "文件预览",
          url: option.url,
          fileType: option.fileType,
          key: option.attachmentId || option.key || Math.uuid(),
          info: {
            owner: option.uploaderName,
            //folder: "path to document",
            uploaded: option.uploadTime,
            // sharingSettings: [
            //   {
            //     user: "user name",
            //     permissions: "<permissions>",
            //     isLink: false,
            //   },
            // ],
            favorite: "true",
          },
          permissions: {
            download: option.permissions.download || true,
            print: option.permissions.print || false,
            edit: option.permissions.edit || false,

            // edit: <can edit>, // default = true
            // download: <can download>, // default = true
            // reader: <can view in readable mode>,
            // review: <can review>, // default = edit
            // print: <can print>, // default = true
            // comment: <can comment in view mode> // default = edit,
            // modifyFilter: <can add, remove and save filter in the spreadsheet> // default = true
            // modifyContentControl: <can modify content controls in documenteditor> // default = true
            // fillForms:  <can edit forms in view mode> // default = edit || review,
            // copy: <can copy data> // default = true,
            // editCommentAuthorOnly: <can edit your own comments only> // default = false
            // deleteCommentAuthorOnly: <can delete your own comments only> // default = false,
            // reviewGroups: ["Group1", ""] // current user can accept/reject review changes made by users from Group1 and users without a group. [] - use groups, but can't change any group's changes
            // commentGroups: { // {} - use groups, but can't view/edit/delete any group's comments
            //      view: ["Group1", ""] // current user can view comments made by users from Group1 and users without a group.
            //      edit: ["Group1", ""] // current user can edit comments made by users from Group1 and users without a group.
            //      remove: ["Group1", ""] // current user can remove comments made by users from Group1 and users without a group.
            // }
          },
        },
        editorConfig: {
          // actionLink: { // open file and scroll to data, used with onMakeActionLink or the onRequestSendNotify event
          //     action: {
          //         type: "bookmark", // or type="comment"
          //         data: <bookmark name> // or comment id
          //     }
          // },
          mode: option.permissions.edit ? "edit" : "view",
          lang: "zh",
          //location: <location>,
          // canCoAuthoring: <can coauthoring documents>,
          // canBackToFolder: <can return to folder> - deprecated. use "customization.goback" parameter,
          // createUrl: 'create document url',
          // sharingSettingsUrl: 'document sharing settings url',
          // fileChoiceUrl: 'source url', // for mail merge or image from storage
          callbackUrl: option.editUrl,
          // mergeFolderUrl: 'folder for saving merged file', // must be deprecated, use saveAsUrl instead
          // saveAsUrl: 'folder for saving files'
          // licenseUrl: <url for license>,
          // customerId: <customer id>,
          // region: <regional settings> // can be 'en-us' or lang code

          user: {
            id: this.user.userId,
            name: this.user.name,
            group: this.user.departmentName, // for customization.reviewPermissions parameter
          },
          // recent: [
          //   {
          //     title: "document title",
          //     url: "document url",
          //     folder: "path to document",
          //   },
          // ],
          customization: {
            about: false,
            // goback: {
            //   url: "http://eip.championsoft.net",
            //   text: "齐明软件综合管理平台",
            //   blank: true,
            //   requestClose: false, // if true - goback send onRequestClose event instead opening url
            // },
            // chat: true,
            // comments: true,
            // zoom: 100,
            // compactToolbar: false,
            // leftMenu: true,
            // rightMenu: true,
            // hideRightMenu: false, // hide or show right panel on first loading
            // toolbar: true,
            // statusBar: true,
            // autosave: true,
            // forcesave: false,
            // commentAuthorOnly: false, // must be deprecated. use permissions.editCommentAuthorOnly and permissions.deleteCommentAuthorOnly instead
            // showReviewChanges: false,
            help: false,
            // compactHeader: false,
            // toolbarNoTabs: false,
            // toolbarHideFileName: false,
            // reviewDisplay: 'original', // original for viewer, markup for editor
            // spellcheck: true,
            // compatibleFeatures: false,
            // unit: 'cm' // cm, pt, inch,
            // mentionShare : true // customize tooltip for mention,
            // macros: true // can run macros in document
            // plugins: true // can run plugins in document
            // macrosMode: 'warn' // warn about automatic macros, 'enable', 'disable', 'warn',
            // trackChanges: undefined // true/false - open editor with track changes mode on/off,
            // hideRulers: false // hide or show rulers on first loading (presentation or document editor)
            // hideNotes: false // hide or show notes panel on first loading (presentation editor)
            // uiTheme: 'theme-dark' // set interface theme: id or default-dark/default-light
          },
        },
      };
      window.docEditor = new DocsAPI.DocEditor("onlyoffice", config);
    },
  },
  watch: {
    option: {
      handler: function (n, o) {
        if (this.initDone && this.modelDone) {
          this.loadDone = false;
          this.modelDone = false;
          this.init();
        }
      },
      deep: true,
    },
  },
};
</script>
<style scoped>
.offcie-container {
  width: 100%;
  height: 100%;
}
</style>
